package com.lshl.lingshang.utils;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.webkit.WebSettings;
import android.webkit.WebView;

import androidx.core.content.ContextCompat;

import com.lshl.lingshang.BuildConfig;
import com.lshl.lingshang.application.MyApplication;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * 客户端通用模块： 读取浏览器、 应用版本名、版本号、SDK 手机品牌、手机型号、Release 屏幕分辨率：宽、高 IMEI、IMSI、UUID
 * 手机联网类型、当前网络是否连接
 *
 * @author mac
 */
public class AppUtil {
    /**
     * 获取上下文对象
     *
     * @return 上下文对象
     */
    public static Context getContext() {
        return MyApplication.getInstance().getApplicationContext();
    }

    /**
     * 读取客户端浏览器UA
     *
     * @return
     */
    public static String getUserAgent(Context context) {
        try {
            WebView webview;
            webview = new WebView(context);
            webview.layout(0, 0, 0, 0);
            WebSettings settings = webview.getSettings();
            return settings.getUserAgentString();
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 获取应用的版本名，对应AndroidManifese的versionName
     *
     * @return
     * @throws Exception
     */
    public static String getVersionName(Context context) {
        String version = "";
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = context.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo;
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            version = packInfo.versionName;

        } catch (NameNotFoundException e) {
        }
        return version;
    }

    /**
     * 获取应用的版本号 对应AndroidManifese的versionCode
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        int versionCode = BuildConfig.VERSION_CODE;
        String versionName = BuildConfig.VERSION_NAME;
        LogUtil.showLog("AppUtil", "getVersionCode.73.[context] versionCode = " + versionCode + " versionName = " + versionName);
        int code = 0;
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = context.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            code = packInfo.versionCode;
            LogUtil.showLog("AppUtil", "getVersionCode.81.[context] code = " + code);
        } catch (NameNotFoundException e) {
        }
        return code;
    }

    /**
     * 获取分辨率：宽
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        int screenWidth = 0;
        try {
            if (context == null) return 0;
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            screenWidth = dm.widthPixels;
        } catch (Exception ex) {
        }
        return screenWidth;
    }

    /**
     * 获取分辨率：高
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        int screenHeight = 0;
        try {
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            screenHeight = dm.heightPixels;
            return screenHeight;
        } catch (Exception ex) {
        }
        return screenHeight;
    }

    /**
     * 获取IMEI
     *
     * @param context
     * @return
     */
    @SuppressLint("MissingPermission")
    public static String getIMEI(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                return tm.getImei();
            } else {
                return tm.getDeviceId();
            }
        } catch (Exception e) {
        }

        return "";
    }


    /**
     * 获取IMSI
     *
     * @param context
     * @return
     */
    public static String getIMSI(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String imsi = tm.getSubscriberId();
            return imsi == null ? "" : imsi;
        } catch (Exception e) {
        }
        return "";
    }

//    /**
//     * 根据IMEI和IMSI生成当前设备的唯一识别码
//     *
//     * @return
//     */
//    public static String getUUID(Context context) {
//        String imei = getIMEI(context);
//        String imsi = getIMSI(context);
//        String uuid = MD5Util.getMD5Encoding(imei + imsi + TimeUtil.getInstance().getStandardDate("yyyyMMddHHmmss"));
//        return uuid;
//    }

    /**
     * 获取SDK号
     *
     * @return
     */
    public static int getSdkVersion() {
        return Build.VERSION.SDK_INT;
    }

    /**
     * 获取设备品牌
     *
     * @return
     */
    public static String getBrand() {
        return Build.BRAND;
    }

    /**
     * 获取设备型号
     *
     * @return
     */
    public static String getDevice() {
        return Build.DEVICE;
    }

    /**
     * 获取Release
     *
     * @return
     */
    public static String getRelease() {
        return Build.VERSION.RELEASE;
    }

    /**
     * ****** 获取当前网络类型 当用wifi上的时候 getType 是 WIFI getExtraInfo是空的 当用手机上的时候 getType
     * 是MOBILE <p/> 用移动CMNET方式 getExtraInfo 的值是cmnet 用移动CMWAP方式 getExtraInfo
     * 的值是cmwap 但是不在代理的情况下访问普通的网站访问不了 <p/> 用联通3gwap方式 getExtraInfo 的值是3gwap
     * 用联通3gnet方式 getExtraInfo 的值是3gnet 用联通uniwap方式 getExtraInfo 的值是uniwap
     * 用联通uninet方式 getExtraInfo 的值是uninet
     *
     * @return
     */
    public static String getNetType(Context context) {
        String netType = "WIFI";
        ConnectivityManager connectionManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        // 获取网络的状态信息，有下面三种方式
        NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();

        if (nType == ConnectivityManager.TYPE_MOBILE) {
            if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {
                netType = "CMNET";
            } else {
                netType = "CMWAP";
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = "WIFI";
        }
        return netType;
    }

    /**
     * 检测网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        if (context == null) return false;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected())
            return true;
        else return false;
    }

    /**
     * 获取屏幕宽高与设计尺寸的比例大小
     *
     * @param context
     * @param designedWidth  设计宽度
     * @param designedHeight 设计高度
     * @return
     */
    public static float getRatio(Context context, int designedWidth, int designedHeight) {
        float screenHeight = AppUtil.getScreenHeight(context);
        float screenWidth = AppUtil.getScreenWidth(context);
        // 横屏下宽高错位
        if (screenHeight < screenWidth) {
            float tmp = screenHeight;
            screenHeight = screenWidth;
            screenWidth = tmp;
        }
        // 开发时屏幕宽高
        float ratioWidth = screenWidth / designedWidth;
        float ratioHeight = screenHeight / designedHeight;

        return Math.max(ratioWidth, ratioHeight);
    }

    /**
     * 获取当前进程名
     *
     * @param context
     * @return 进程名
     */
    public static final String getProcessName(Context context) {
        String processName = null;

        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
        while (true) {
            for (ActivityManager.RunningAppProcessInfo info : am.getRunningAppProcesses()) {
                if (info.pid == android.os.Process.myPid()) {
                    processName = info.processName;

                    break;
                }
            }

            // go home
            if (!TextUtils.isEmpty(processName)) {
                return processName;
            }

            // take a rest and again
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 权限判断
     *
     * @param permission
     * @return
     */
    public static boolean checkPermission(String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return ContextCompat.checkSelfPermission(MyApplication.getInstance(), permission) == PackageManager.PERMISSION_GRANTED;
        }
        return true;
    }

    /**
     * 根据IMEI和IMSI生成当前设备的唯一识别码
     *
     * @return
     */
    public static String getUUID(Context context) {
        String imei = getIMEI(context);
        String imsi = getIMSI(context);
//        String uuid = MD5Util.getMD5Encoding(imei + imsi + TimeUtil.getInstance().getStandardDate("yyyyMMddHHmmss"));
        String uuid = MD5Util.getMD5(imei + imsi);
        return uuid;
    }


    /**
     * 获取手机ip地址 * * @return
     */
    public static String getIP() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { //
                        if (!inetAddress.isLoopbackAddress() && inetAddress
                                instanceof Inet6Address) {
                            return inetAddress.getHostAddress().toString();
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
        return "";
    }

    /**
     * 判断是否是 主线程
     *
     * @return
     */
    public static boolean inMainProcess(Context context) {
        String packageName = context.getPackageName();
        String processName = getProcessName(context);
        return packageName.equals(processName);
    }

    /**
     * 获取系统状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }


    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    public static String getBuglyProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    public static int dpToPx(Context context, int dps) {
        return Math.round(context.getResources().getDisplayMetrics().density * dps);
    }

    public static int dpToSp(Context context, int pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }


}